package rbac

import (
	"fmt"
	"gitee.com/enzolwb/my-web-scaffold/api"
	"gitee.com/enzolwb/my-web-scaffold/models"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	con "gitee.com/enzolwb/my-web-scaffold/pkg/const"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"github.com/EnzoLwb/cuslog"
	"github.com/casbin/casbin"
	"github.com/gin-gonic/gin"
)

func Authorize(e *casbin.Enforcer) gin.HandlerFunc {
	return func(c *gin.Context) {
		//通过session 或者 jwt 或者 token 获取用户信息
		sessionInfo, ok := c.Get(con.CTX_USERSESSION_KEY)
		if !ok {
			cuslog.Warn("Authorize 获取session信息失败")
			app.Response(c, ecode.ErrServer)
			return
		}
		userInfo := sessionInfo.(*api.SessUserInfo)

		//查询用户的角色
		role := &models.Role{}
		sub, err := role.GetRoleNameByUid(userInfo.ID)
		if err != nil {
			app.Response(c, ecode.ErrServer)
			c.Abort()
		}

		//如果是超级管理员就不需要验证了
		if sub == "admin" {
			fmt.Println("你是管理员 咱就不验证了~")
			c.Next()
		} else {
			//获取请求的URI
			obj := c.Request.URL.RequestURI()
			//获取请求方法
			act := c.Request.Method
			fmt.Println(obj, act, sub)
			//判断策略中是否存在
			if ok := e.Enforce(sub, obj, act); ok {
				fmt.Println("恭喜您,权限验证通过")
				c.Next()
			} else {
				app.Response(c, ecode.ErrNoPermission)
				c.Abort()
			}
		}

	}
}
